namespace UserVoiceApi
{
    using System.Collections.Generic;
    using System.Net;
    using System.Web.Helpers;

    public static class Api
    {
        private const string BaseApiUrl = "http://{0}.uservoice.com/api/v1/{1}.json?client={2}";
    
        public static IList<dynamic> GetForumList(string site, string apiKey)
        {
            string apiUrl = string.Format(BaseApiUrl, site, "forums", apiKey);

            var response = GetJsonResponse(apiUrl);

            return new List<dynamic>(response.Forums);
        }

        public static dynamic GetForum(string forumId, string site, string apiKey)
        {
            string apiUrl = string.Format(BaseApiUrl, site, "forums/" + forumId, apiKey);

            var response = GetJsonResponse(apiUrl);

            return response.Forum;
        }

        public static IList<dynamic> GetSuggestionsList(string forumId, string site, string apiKey)
        {
            string apiUrl = string.Format(BaseApiUrl, site, "forums/" + forumId + "/suggestions", apiKey);

            var response = GetJsonResponse(apiUrl);

            return new List<dynamic>(response.suggestions);
        }

        public static IList<dynamic> GetSuggestionsSearch(string forumId, string query, string site, string apiKey)
        {
            string apiUrl = string.Format(BaseApiUrl + "&query={3}", site, "forums/" + forumId + "/suggestions/search", apiKey, query);

            var response = GetJsonResponse(apiUrl);

            return new List<dynamic>(response.suggestions);
        }
        
        public static IList<dynamic> GetCommentsForSuggestions(string suggestionId, string forumId, string site, string apiKey)
        {
            string apiUrl = string.Format(BaseApiUrl, site, "forums/" + forumId + "/suggestions/" + suggestionId + "/comments", apiKey);

            var response = GetJsonResponse(apiUrl);

            return new List<dynamic>(response.comments);
        }

        private static dynamic GetJsonResponse(string apiUrl)
        {
            var client = new WebClient();

            var jsonResponse = client.DownloadString(apiUrl);
            return Json.Decode(jsonResponse);
        }
    }
}